package com.creditease.tmsp.modules.sys.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.creditease.tmsp.common.config.Global;
import com.creditease.tmsp.common.web.BaseController;
import com.creditease.tmsp.modules.sys.entity.SysResource;
import com.creditease.tmsp.modules.sys.service.SysResourceService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * 
 * @Description：资源Controller
 * @author：
 * @CreateDate：
 * @Company:
 * @version V1.0
 */

@Controller
@RequestMapping(value = "${adminPath}/sys/resource")
public class SysResourceController extends BaseController {

	@Autowired
	private SysResourceService sysResourceService;

	@ModelAttribute
	public SysResource get(@RequestParam(required = false) String id) {
		if (StringUtils.isNotBlank(id)) {
			return sysResourceService.getById(id);
		} else {
			return new SysResource();
		}
	}

	@RequestMapping(value = { "list", "" })
	public String list(Model model,HttpServletRequest request) {
		List<SysResource> list = Lists.newArrayList();
		List<SysResource> resourcelist = sysResourceService.findAllMenu();
		SysResource.sortList(list, resourcelist, "1");
		model.addAttribute("list", list);
		return "modules/sys/sysResourceList";
	}

	@RequestMapping(value = "form")
	public String form(SysResource sysResource, Model model, HttpServletRequest request) {
		
		String param = request.getParameter("action");
		
		if("save".equals(param)){
			if (sysResource.getParentId() == null) {
				sysResource.setParent(new SysResource("1"));
			}
			sysResource.setParent(sysResourceService.getById(sysResource.getParent().getId()));
		}else if("update".equals(param)){
			if (sysResourceService.getById(sysResource.getId()).getParentId() == null) {
				sysResource.setParent(new SysResource("1"));
			}
			sysResource.setParent(sysResourceService.getById(sysResourceService.getById(sysResource.getId()).getParentId()));
			
		}else{
			
			if (sysResource.getParentId() == null) {
				sysResource.setParent(new SysResource("1"));
			}
			sysResource.setParent(sysResourceService.getById(sysResource.getParentId()));
		}
		
		model.addAttribute("sysResource", sysResource);
		return "modules/sys/sysResourceForm";
	}
	
	
	@RequestMapping(value = "save")
	public String save(SysResource sysResource, Model model,
			RedirectAttributes redirectAttributes, HttpServletRequest request) {
		if (!beanValidator(model, sysResource)) {
			return form(sysResource, model,request);
		}
		
		if(StringUtils.isNotBlank(sysResource.getId())){
			sysResourceService.updateSysResource(sysResource);
		}else{
			sysResourceService.saveSysResource(sysResource);
		}
		
		addMessage(redirectAttributes, "保存菜单'" + sysResource.getName() + "'成功");
		return "redirect:" + Global.getAdminPath() + "/sys/resource/";
	}

	
	@RequestMapping(value = "delete")
	public String delete(String id, RedirectAttributes redirectAttributes) {
		if (SysResource.isRoot(id)) {
			addMessage(redirectAttributes, "删除菜单失败, 不允许删除顶级菜单或编号为空");
		} else {
			sysResourceService.delete(id);
			addMessage(redirectAttributes, "删除菜单成功");
		}
		return "redirect:" + Global.getAdminPath() + "/sys/resource/";
	}

	@RequiresUser
	@RequestMapping(value = "tree")
	public String tree() {
		return "modules/sys/sysResourceTree";
	}

	/**
	 * 批量修改菜单排序
	 */
	
	@RequestMapping(value = "updateSort")
	public String updateSort(String[] ids, Integer[] sorts,
			RedirectAttributes redirectAttributes) {
		int len = ids.length;
		SysResource[] sysResource = new SysResource[len];
		for (int i = 0; i < len; i++) {
			sysResource[i] = sysResourceService.getById(ids[i]);
			sysResource[i].setSort(sorts[i]);
			sysResourceService.save(sysResource[i]);

		}
		addMessage(redirectAttributes, "保存菜单排序成功!");
		return "redirect:" + Global.getAdminPath() + "/sys/resource/";
	}

	@RequiresUser
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(SysResource sysResource,
			@RequestParam(required = false) Long extId,
			HttpServletResponse response, HttpServletRequest request) {
		response.setContentType("application/json; charset=UTF-8");
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<SysResource> list = sysResourceService.findAllMenu();
		for (int i = 0; i < list.size(); i++) {
			SysResource e = list.get(i);
			if (extId == null|| (extId != null && !extId.equals(e.getId()) && e.getParentIds().indexOf("," + extId + ",") == -1)) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getId());
				map.put("pId", e.getParentId() != null ? e.getParentId(): 0);
				map.put("name", e.getName());
				mapList.add(map);
			}
		}
		return mapList;
	}
}